package com.example.NetworkSender.network;

import android.util.Log;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class NetworkListener implements Runnable {

    public final Object lockObj = new Object();
    private final int port;
    public boolean hasNewData;
    public int[] buffer;
    public int size;
    private boolean isTimeToDie = false;

    public NetworkListener(int port) {
        this.port = port;
        buffer = new int[10];
        hasNewData = false;
    }

    @Override
    public void run() {
        try {
            boolean shouldStop = false;
            ServerSocket serv = new ServerSocket(port);
            while (!shouldStop) {
                Socket neighbourSocket = serv.accept();
                InputStream socketStream = neighbourSocket.getInputStream();
                Scanner scanner = new Scanner(socketStream);
                synchronized (lockObj) {
                    shouldStop = isTimeToDie;
                    if (scanner.hasNext() && !hasNewData) {
                        int sizeToReceive = scanner.nextInt();
                        for (int i = 0; i < sizeToReceive; i++) {
                            buffer[i] = scanner.nextInt();
                        }
                        size = sizeToReceive;
                        hasNewData = true;
                        neighbourSocket.close();
                    }
                }
                Thread.sleep(200);
            }
        } catch (Exception ex) {
            Log.e("NetworkListener.run", "EXCEPTION  " + ex.getMessage() + "   !");
        }
    }

    public void stop() {
        synchronized (lockObj) {
            isTimeToDie = true;
        }
    }
}
